package mqLog

import (
	"os"
	"os/exec"
	"path/filepath"
	"sieve_engine/lib/log"
	"sieve_engine/lib/timesched"
	uTime "sieve_engine/lib/util/time"
	"time"
)

func createCrontab() {
	sch, err := timesched.Parse("h0m0s59")
	if err != nil {
		log.Err(err)
		return
	}
	sch.Start(func(t time.Time) {
		for _, info := range logFileList {
			info.tarZipFile()
			info.removeTarZipFile()
		}
	})
}

func (t *logFileInfo) tarZipFile() {
	if !t.FileLogTarStatus {
		return
	}
	lastTime := time.Now().AddDate(0, 0, -1)
	logDir := filepath.Join(*logFileDir, uTime.FmtDate(lastTime, "Ym"))
	exist, _ := PathExists(logDir)
	if !exist {
		return
	}
	lastFileName := t.FileNamePrefix + uTime.FmtDate(lastTime, "Ymd")
	cmd := exec.Command("tar", "zcvf", lastFileName+".tar.gz", lastFileName+".log")
	cmd.Dir = logDir
	err := cmd.Run()
	if err != nil {
		log.Err(logDir, lastFileName+".tar.gz", lastFileName+".log", err)
	} else {
		os.Remove(filepath.Join(logDir, lastFileName+".log"))
	}
}

func (t *logFileInfo) removeTarZipFile() {
	lastTime := time.Now().AddDate(0, 0, -t.FileLogReserveDay)
	dirName := filepath.Join(*logFileDir, uTime.FmtDate(lastTime, "Ym"))
	exist, _ := PathExists(dirName)
	if !exist {
		return
	}
	suffix := ".log"
	if t.FileLogTarStatus {
		suffix = ".tar.gz"
	}
	fileName := filepath.Join(dirName, t.FileNamePrefix+uTime.FmtDate(lastTime, "Ymd")+suffix)
	if exist, _ := PathExists(fileName); !exist {
		log.Err(fileName, "not exist")
		return
	}
	os.Remove(fileName)
}
